package demo2_example;

class Money implements Cloneable{
    double m ;

    public Money(double money) {
        this.m = money;
    }

    @Override
    public String toString() {
        return  m + "";
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
//表明该类支持克隆
class Person implements Cloneable{
    Money money ;
    private int age;

    public Person(Money money, int age) {
        this.money = money;
        this.age = age;
    }

    //protected修饰，在不同包的子类中调用应用super
    @Override
    protected Object clone() throws CloneNotSupportedException {
        //若只进行到这一步则为浅拷贝，money对象没有被拷贝，仍指向同一个地址
        //return super.clone();
        //深拷贝，将Person对象中的money这个引用也进行拷贝
        Person tmp = (Person) super.clone();
        //money已经将clone方法重写，所以不用super调用
        tmp.money = (Money) this.money.clone();
        return tmp;
    }

    @Override
    public String toString() {
        return "Person{" +
                "money=" + money +
                ", age=" + age +
                '}';
    }
}

public class testClone{
    public static void main(String[] args) throws CloneNotSupportedException {
        Money money = new Money(19.9);
        Person person = new Person(money,19);
        Person person2 = (Person) person.clone();
        System.out.println(person2);
        person2.money.m = 99.9;
        System.out.println(person.money.m);
        System.out.println(person2.money.m);
    }
}
